using System;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Web;


/// <summary>
/// Summary description for Phantrang
/// </summary>
/// 
namespace webapp4U.UI
{
    public class Pager : Label, INamingContainer
    {
        LinkButton previousButton;
        LinkButton nextButton;
        LinkButton firstButton;
        LinkButton lastButton;
        LinkButton[] pagingLinkButtons;

        HttpContext context;

        #region "GetIntFromQueryString"
        public static int GetIntFromQueryString(HttpContext context, string key)
        {
            int returnValue = -1;
            string queryStringValue;

            // Attempt to get the value from the query string
            //
            queryStringValue = HttpContext.Current.Request.QueryString[key];

            // If we didn't find anything, just return
            //
            if (queryStringValue == null)
                return returnValue;

            // Found a value, attempt to conver to integer
            //
            try
            {

                // Special case if we find a # in the value
                //
                if (queryStringValue.IndexOf("#") > 0)
                    queryStringValue = queryStringValue.Substring(0, queryStringValue.IndexOf("#"));

                returnValue = Convert.ToInt32(queryStringValue);
            }
            catch { }

            return returnValue;

        }

        public int GetPageIndex()
        {
            context = HttpContext.Current;
            //return GetIntFromQueryString(context, "PageIndex");
            return 1;

        }
        #endregion
                   

        public override ControlCollection Controls
        {
            get
            {
                EnsureChildControls();
                return base.Controls;
            }
        }


        protected override void CreateChildControls() 
        {
            //HttpContext.Current.Response.Write("CreateChildControls()  ");
            Controls.Clear();
                                       
            AddPageButtons();

            AddFirstLastLinkButtons();

            AddPreviousNextLinkButtons();
            
        }

        protected override void Render(HtmlTextWriter writer)
        {
            //HttpContext.Current.Response.Write("Render()  ");
            AddAttributesToRender(writer);


            // Render the paging buttons
            //
            writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass, false);
            
            RenderFirst(writer);

            RenderPrevious(writer);

            RenderPagingButtons(writer);

            RenderNext(writer);

            RenderLast(writer);


        }


        void RenderFirst(HtmlTextWriter writer)
        {

            int totalPages = CalculateTotalPages();

            if ((PageIndex >= 3) && (totalPages > 5))
            {
                firstButton.RenderControl(writer);

                LiteralControl l = new LiteralControl("&nbsp;...&nbsp;");
                l.RenderControl(writer);
            }
            //else 
            //{
            //    Literal l = new Literal();
            //    l.Text = "&nbsp;<font color=#CCCCCC size=0.8em>First</font>&nbsp;";
            //    l.RenderControl(writer);
            //}
        }

        void RenderLast(HtmlTextWriter writer)
        {

            int totalPages = CalculateTotalPages();

            if (((PageIndex + 3) < totalPages) && (totalPages > 5))
            {
                LiteralControl l = new LiteralControl("&nbsp;...&nbsp;");
                l.RenderControl(writer);

                lastButton.RenderControl(writer);
            }
            //else
            //{
            //    Literal l = new Literal();
            //    l.Text = "&nbsp;<font color=#CCCCCC size=0.8em>Last</font>&nbsp;";
            //    l.RenderControl(writer);
            //}

        }

        void RenderPrevious(HtmlTextWriter writer)
        {
            Literal l;

            if (HasPrevious)
            {
                previousButton.RenderControl(writer);

                l = new Literal();
                l.Text = "&nbsp;";
                l.RenderControl(writer);
            }
            //else
            //{
            //    l = new Literal();
            //    l.Text = "<font color=#CCCCCC size=0.8em> Prev </font> &nbsp;";
            //    l.RenderControl(writer);
            //}

        }

        void RenderNext(HtmlTextWriter writer)
        {
            Literal l;

            if (HasNext)
            {

                l = new Literal();
                l.Text = "&nbsp;";
                l.RenderControl(writer);

                nextButton.RenderControl(writer);
            }
            // else 
            //{
            //    l = new Literal();
            //    l.Text = "&nbsp;<font color=#CCCCCC size=0.8em>Next</font>&nbsp;";
            //    l.RenderControl(writer);
            //}

        }



        void RenderPagingButtons(HtmlTextWriter writer)
        {
            int totalPages;
            
            totalPages = CalculateTotalPages();

            // If we have <= 5 pages display all the pages and exit
            //
            if (totalPages <= 5)
            {
                RenderButtonRange(0, totalPages, writer);
            }
            else
            {

                int lowerBound = (PageIndex - 2);
                int upperBound = (PageIndex + 3);

                if (lowerBound <= 0)
                    lowerBound = 0;

                if (PageIndex == 0)
                    RenderButtonRange(0, 5, writer);

                else if (PageIndex == 1)
                    RenderButtonRange(0, (PageIndex + 4), writer);

                else if (PageIndex < (totalPages - 2))
                    RenderButtonRange(lowerBound, (PageIndex + 3), writer);

                else if (PageIndex == (totalPages - 2))
                    RenderButtonRange((totalPages - 5), (PageIndex + 2), writer);

                else if (PageIndex == (totalPages - 1))
                    RenderButtonRange((totalPages - 5), (PageIndex + 1), writer);
            }
           
        }

        void RenderButtonRange(int start, int end, HtmlTextWriter writer)
        {

            for (int i = start; i < end; i++)
            {
                // Are we working with the selected index?
                
                if (PageIndex == i+1)
                {
                    Literal l = new Literal();
                    l.Text = "[<span class=\"currentPage\">" + (i + 1).ToString() + "</span>]";
                    l.RenderControl(writer);
                }
                else
                {
                    //try
                   // {
                        pagingLinkButtons[i].RenderControl(writer);
                   // }
                   // catch { }
                }
                if (i < (end - 1))
                    writer.Write(" ");
            }
        }


        void AddPageButtons()
        {

            // First add the lower page buttons
            //
            pagingLinkButtons = new LinkButton[CalculateTotalPages()];

            // Create the buttons and add them to 
            // the Controls collection
            //
            for (int i = 0; i < pagingLinkButtons.Length; i++)
            {

                pagingLinkButtons[i] = new LinkButton();
                pagingLinkButtons[i].EnableViewState = false;
                pagingLinkButtons[i].Text = (i + 1).ToString();
                pagingLinkButtons[i].ID = i.ToString();
                pagingLinkButtons[i].CommandArgument = (i+1).ToString();
                pagingLinkButtons[i].Click += new System.EventHandler(PageIndex_Click);
                Controls.Add(pagingLinkButtons[i]);

            }

        }

        void AddFirstLastLinkButtons()
        {
            // Create the previous button if necessary
            //
            firstButton = new LinkButton();
            firstButton.ID = "First";
            firstButton.Text = "First";
            firstButton.CommandArgument = "1";
            firstButton.Click += new System.EventHandler(PageIndex_Click);
            Controls.Add(firstButton);

            // Create the next button if necessary
            //
            lastButton = new LinkButton();
            lastButton.ID = "Last";
            lastButton.Text = "Last";
            lastButton.CommandArgument = CalculateTotalPages().ToString();
            lastButton.Click += new System.EventHandler(PageIndex_Click);
            Controls.Add(lastButton);

        }

        void AddPreviousNextLinkButtons() 
        {

            // nut Next 
            nextButton = new LinkButton();
            nextButton.ID = "Next";
            nextButton.Text = "Next";
            nextButton.CommandArgument = (PageIndex + 1).ToString();
            nextButton.Click += new System.EventHandler(PageIndex_Click);
            Controls.Add(nextButton);

            // nut Prev
            previousButton = new LinkButton();
            previousButton.ID = "Prev";
            previousButton.Text = "Prev";
            previousButton.CommandArgument = (PageIndex - 1).ToString();
            previousButton.Click += new System.EventHandler(PageIndex_Click);
            Controls.Add(previousButton);

        }


        public event System.EventHandler IndexChanged;

        // *********************************************************************
        //  PageIndex_Click
        //
        /// <summary>
        /// Event raised when a new index is selected from the paging control
        /// </summary>
        /// 
        // ********************************************************************/

        #region Events
        void PageIndex_Click(Object sender, EventArgs e)
        {
            PageIndex = Convert.ToInt32(((LinkButton)sender).CommandArgument);

            if (null != IndexChanged)
                IndexChanged(sender, e);

        }
        #endregion


        public int PageIndex
        {
            get
            {
                int _pageIndex = 0;

                if (!Page.IsPostBack)
                {
                    _pageIndex = 1;
                    ViewState["PageIndex"] = 1;
                    
                }
                else
                {
                    _pageIndex = Convert.ToInt32(ViewState["PageIndex"]);

                }


                if (_pageIndex < 0)
                    return 1;
                else
                    return _pageIndex;
            }
            set
            {
                ViewState["PageIndex"] = value;
            }
        }



        public int PageSize
        {
            get
            {
                int pageSize = Convert.ToInt32(ViewState["PageSize"]);
                return pageSize;
            }
            set
            {
                ViewState["PageSize"] = value;
            }

        }

        public int TotalRecords
        {
            get
            {
                return Convert.ToInt32(ViewState["TotalRecords"]);
            }
            set
            {
                ViewState["TotalRecords"] = value;
                
            }
        }


        //  tinh xem co bao nhieu trang
        public int CalculateTotalPages()
        {
            int totalPagesAvailable;

            if (TotalRecords == 0)
                return 0;

            // First calculate the division
            //
            totalPagesAvailable = TotalRecords / PageSize;

            // Now do a mod for any remainder
            //
            if ((TotalRecords % PageSize) > 0)
                totalPagesAvailable++;

            return totalPagesAvailable;

        }


        #region Private Properties
        private bool HasPrevious
        {
            get
            {
                if (PageIndex > 1)
                    return true;

                return false;
            }
        }

        private bool HasNext
        {
            get
            {
                if (PageIndex < CalculateTotalPages())
                    return true;

                return false;
            }
        }
        #endregion

    }
}
